package com.mo.web;

import com.mo.pojo.SysUser;
import com.mo.service.SysUserService;
import com.mo.web.pojo.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping
    public JsonResult doFindUser(SysUser sysUser) {

        return new JsonResult(sysUserService.findUser(sysUser));

    }


    //    @RequiresPermissions("user:add")
    @PostMapping
    public JsonResult doSaveUser(@RequestBody SysUser user) {//Json反系列化
        sysUserService.saveUser(user);
        return new JsonResult("save ok");//Json系列化

    }

    @GetMapping("{uCode}")
    public JsonResult doFindById(@PathVariable Long uCode) {

        return new JsonResult(sysUserService.findById(uCode));
    }


    @RequiresPermissions("user:update")
    @PutMapping
    public JsonResult doUpdateUser(@RequestBody SysUser user) { //Jason反序列化
        sysUserService.updateUser(user);
        return new JsonResult("update ok");
    }

    @RequiresPermissions("user:delete")
    @DeleteMapping("{uCode}")
    public JsonResult doDeleteNoticeById(@PathVariable Long uCode) {
        sysUserService.deleteById(uCode);
        return new JsonResult("delete ok");
    }


    //添加处理登录请求的方法

    @GetMapping("login/{uName}/{uPwd}")
    public JsonResult doLogin(@PathVariable String uName,
                              @PathVariable String uPwd) {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token =
                new UsernamePasswordToken(uName, uPwd);
        subject.login(token);
        return new JsonResult("login ok");
    }

    @PatchMapping("/password/{sourcePassword}/{newPassword}/{confirmPassword}")
    public JsonResult doUpdatePassword(@PathVariable String sourcePassword,
                                       @PathVariable String newPassword,
                                       @PathVariable String confirmPassword
    ) {
        sysUserService.updatePassword(
                sourcePassword,
                newPassword,
                confirmPassword);
        return new JsonResult("Password update O8K");

    }
}